package com.gxb.codebook;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import io.alterac.blurkit.BlurKit;
import io.alterac.blurkit.BlurLayout;

public class ForgetActivity extends AppCompatActivity {

    private EditText Username;
    private EditText Password;
    private EditText Password2;
    private EditText MiBao1;
    private EditText MiBao2;
    private EditText MiBao3;
    private Button reg_btn;
    private BlurLayout blurLayout;
    private BroadcastReceiver themeChangeReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_forget);
        BlurKit.init(this);

        Username = findViewById(R.id.username);
        Password = findViewById(R.id.one_password);
        Password2 = findViewById(R.id.two_password);
        reg_btn = findViewById(R.id.reg_btn);
        MiBao1 = findViewById(R.id.mibao1);
        MiBao2 = findViewById(R.id.mibao2);
        MiBao3 = findViewById(R.id.mibao3);
        blurLayout = findViewById(R.id.blurLayout);

        // 初始化LocalBroadcastManager
        localBroadcastManager = LocalBroadcastManager.getInstance(this);

        // 初始化广播接收器
        themeChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("THEME_CHANGED".equals(intent.getAction())) {
                    recreate();
                }
            }
        };

        // 注册广播接收器
        IntentFilter filter = new IntentFilter("THEME_CHANGED");
        localBroadcastManager.registerReceiver(themeChangeReceiver, filter);

        reg_btn.setOnClickListener(v -> {
            String username = Username.getText().toString();
            String password = Password.getText().toString();
            String password2 = Password2.getText().toString();
            String mibao1 = MiBao1.getText().toString();
            String mibao2 = MiBao2.getText().toString();
            String mibao3 = MiBao3.getText().toString();

            if (username.isEmpty() || password.isEmpty() || password2.isEmpty() ||
                    mibao1.isEmpty() || mibao2.isEmpty() || mibao3.isEmpty()) {
                Toast.makeText(ForgetActivity.this, "请填写完整信息", Toast.LENGTH_SHORT).show();
            } else if (!password.equals(password2)) {
                Toast.makeText(ForgetActivity.this, "两次密码不一致", Toast.LENGTH_SHORT).show();
            } else if (!username.matches("^[A-Za-z0-9@#$%^&*.]+$") ||
                    !password.matches("^[A-Za-z0-9@#$%^&*.]+$")) {
                Toast.makeText(ForgetActivity.this, "用户名和密码仅支持A-Z,a-z,0-9,@、#、$、%、^、&、*、.",
                        Toast.LENGTH_SHORT).show();
            } else {
                String wserpasswd = password + "+" + username;
                if (mibao("你的家乡是：" + mibao1) == 0 ||
                        mibao("你的宠物是：" + mibao2) == 0 ||
                        mibao("你的学校是：" + mibao3) == 0) {
                    Toast.makeText(ForgetActivity.this, "密保问题错误", Toast.LENGTH_SHORT).show();
                } else {
                    String encryptedPassword = UserPasswdConfound.encrypt(wserpasswd);
                    saveUserInfoToFile(encryptedPassword);
                    Toast.makeText(ForgetActivity.this, "修改成功", Toast.LENGTH_SHORT).show();

                    // 发送密码修改成功的广播
                    Intent intent = new Intent("PASSWORD_CHANGED");
                    intent.putExtra("username", username);
                    localBroadcastManager.sendBroadcast(intent);

                    finish();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (themeChangeReceiver != null && localBroadcastManager != null) {
            try {
                localBroadcastManager.unregisterReceiver(themeChangeReceiver);
            } catch (IllegalArgumentException e) {
                // 处理接收器未注册的情况
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        blurLayout.startBlur();
        blurLayout.lockView();
    }

    @Override
    protected void onStop() {
        super.onStop();
        blurLayout.pauseBlur();
    }

    private void saveUserInfoToFile(String encryptedPassword) {
        String userInfo = encryptedPassword + "\n";
        File file = new File(getFilesDir(), "user_info.txt");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            try (FileOutputStream fos = new FileOutputStream(file, false)) {
                fos.write(userInfo.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private int mibao(String mibao) {
        File file = new File(getFilesDir(), "mibao.txt");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            try (FileInputStream fis = new FileInputStream(file);
                 InputStreamReader reader = new InputStreamReader(fis)) {
                char[] buffer = new char[1024];
                int len;
                while ((len = reader.read(buffer)) != -1) {
                    String content = new String(buffer, 0, len);
                    if (content.contains(mibao)) {
                        return 1;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
